package com.itibo.common;
import com.itibo.models.Document;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

@ManagedBean
@RequestScoped
public class DownloadBean {
    @ManagedProperty(value = "#{songsBean}")
    SongsBean songsBean;

//    public String getDownload(){
//        Document doc = songsBean.exportDocument();
//        // file download headers
//        return "" + doc.getBody();
//    }
   public void download() throws IOException {
        Document doc=songsBean.exportDocument();
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
        //ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + "1.csv" + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
        OutputStream output = ec.getResponseOutputStream();
        // Now you can write the InputStream of the file to the above OutputStream the usual way.
        // ...
        output.write(doc.getBody().getBytes());
        fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
   }

    public SongsBean getSongsBean() {
        return songsBean;
    }

    public void setSongsBean(SongsBean songsBean) {
        this.songsBean = songsBean;
    }
}
